package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdmMapper;
import com.heima.admin.service.AdmService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lzq
 * @data 2023/5/9 10:46
 */
@Service
public class AdmServiceImpl extends ServiceImpl<AdmMapper, AdUser> implements AdmService {

    /**
     * 管理员登录
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult Login(AdUserDto adUserDto) {
        //1数据校验
        //1.检查参数
        if(StringUtils.isBlank(adUserDto.getName()) || StringUtils.isBlank(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码为空");
        }
        //2查询数据
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        //判断用户是否存在
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断密码是否正确
        String salt = adUser.getSalt();
        String pd = adUserDto.getPassword();
        //加盐
        pd= DigestUtils.md5DigestAsHex((salt + pd).getBytes());
        if (adUser.getPassword().equals(pd)){
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken((long)adUser.getId()));
            //密码和盐不返回
            adUser.setPassword("");
            adUser.setSalt("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }
        //密码错误
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }
}
